package com.smartcanteen.dish.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.smartcanteen.constant.MessageConstant;
import com.smartcanteen.dish.domain.dto.CategoryDTO;
import com.smartcanteen.dish.domain.dto.CategoryTypePageDTO;
import com.smartcanteen.dish.domain.entity.Category;
import com.smartcanteen.dish.mapper.CategoryMapper;
import com.smartcanteen.dish.service.CategoryService;
import com.smartcanteen.result.PageResult;
import com.smartcanteen.security.utils.SecurityUtils;
import com.smartcanteen.system.api.clients.SetmealClient;
import com.smartcanteen.system.api.domain.dto.SetmealDTO;

import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
@AllArgsConstructor
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    private final SetmealClient setmealClient;

    /**
     * 新增分类
     *
     * @param categoryDTO
     */
    @Transactional
    public void addCategory(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);

        if (categoryDTO.getSort() == null)
            category.setSort(100);//默认为100
        if (category.getStatus() == null)
            category.setStatus(1);  // 默认启用
        // 获取当前用户ID
        Long userid = SecurityUtils.getUserId();
        category.setMerchantId(userid);
        categoryMapper.add(category);
        if (category.getType() == 2) {//如果是套餐类型，则将数据同步插入套餐表中
            Category currentCategory = categoryMapper.getByName(category.getName());
            SetmealDTO setmealDTO = new SetmealDTO();
            setmealDTO.setName(currentCategory.getName());
            setmealDTO.setCategoryId(currentCategory.getId());
            setmealDTO.setStatus(currentCategory.getStatus());
            setmealDTO.setPrice(BigDecimal.valueOf(0));
            setmealClient.addSetmealForApi(setmealDTO);
        }
    }

    @Override
    public void addCategoryForApi(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        if (categoryDTO.getSort() == null)
            category.setSort(100);//默认为100
        if (category.getStatus() == null)
            category.setStatus(1);  // 默认启用
        categoryMapper.add(category);
    }

    /**
     * 根据type条件分页查询
     *
     * @param categoryTypePageDTO
     * @return
     */
    public PageResult getPageList(CategoryTypePageDTO categoryTypePageDTO) {
        PageHelper.startPage(categoryTypePageDTO.getPage(), categoryTypePageDTO.getPageSize());
        Page<Category> pagelist = categoryMapper.getPageList(categoryTypePageDTO);
        return new PageResult(pagelist.getTotal(), pagelist.getResult());
    }

    /**
     * 获取所有分类列表
     *
     * @return
     */
    public List<Category> getList(Long merchantId) {
        List<Category> categoryList = categoryMapper.getList(merchantId);
        return categoryList;
    }

    /**
     * 根据id查询分类
     *
     * @param id
     * @return
     */
    public Category getById(Integer id) {
        return categoryMapper.getById(id);
    }

    /**
     * 更新分类信息
     *
     * @param categoryDTO
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    public void udpate(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        categoryMapper.update(category);
        // 如果为套餐类型，则将数据同步修改套餐售卖状态为停售
        if (category.getType() == 2) {
            setmealClient.onOffForApi(category.getId());
        }
    }

    /**
     * 根据id删除分类
     *
     * @param ids
     */
    @GlobalTransactional(rollbackFor = Exception.class)
//    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<Integer> ids) {
        log.info("Seata全局事务id=================>{}", RootContext.getXID());
        List<Integer> isSetmeal = new ArrayList<>();
        if (!ids.isEmpty()) {
            for (Integer id : ids) {
                Category category = categoryMapper.getById(id);
                if (category.getType() == 2) {//如果是套餐类型，则将数据同步删除套餐表中
                    isSetmeal.add(id);
                }
            }
        }
        // 如果有套餐类型，则将数据同步删除套餐表中
        if (!isSetmeal.isEmpty()) {
            try {
                setmealClient.deleteBatchForApi(isSetmeal);
            } catch (Exception e) {
                throw new RuntimeException(MessageConstant.SETMEAL_ON_SALE);
            }
        }
        categoryMapper.deleteBatch(ids);
    }

    @Override
    public Category getByName(String name) {
        return categoryMapper.getByName(name);
    }

    /**
     * 分类起售/停售
     */
    public void onOff(Integer id) {
        categoryMapper.onOff(id);
    }
}
